package com.atguigu.gulimall.product.exception;

import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 集中处理异常
 * @Auther zhaolei
 * @Date 2022-05-05 下午2:47
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.atguigu.gulimall.product.controller")
public class ExceptionControllerAdavice {

    /**
     * 数据校验异常统一处理方法
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handlerEexception (MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        Map<Object, Object> errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach(item->{
            String defaultMessage = item.getDefaultMessage();
            String field = item.getField();
            errorMap.put(field,defaultMessage);
        });
        return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(),BizCodeEnume.VAILD_EXCEPTION.getMsg()).put("data",errorMap);
    }

    //@ExceptionHandler(value = Throwable.class)
    //public R otherExcepiton(Throwable throwable){
    //    return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(),BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    //}
}
